package de.jenseins.utils.propertytranslator.gui.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;

import javax.swing.JOptionPane;

import com.google.api.translate.Language;

import de.jenseins.utils.propertytranslator.PropertyTranslator;
import de.jenseins.utils.propertytranslator.gui.MainFrame;

/**
 * 
 * 
 * @author Jens Greive
 * @since 02.12.2009
 * 
 */
public class StartTranslationListener implements ActionListener {

	private MainFrame mainFrame;

	public StartTranslationListener(MainFrame mainFrame) {
		this.mainFrame = mainFrame;
	}

	public void actionPerformed(ActionEvent e) {
		final File sourceFile = mainFrame.getSourceFile();
		final Language sourceLang = mainFrame.getSourceLanguage();
		final Language[] targetLanguages = mainFrame.getTargetLanguages();
		mainFrame.enableTranslateButton(false);
		mainFrame.enableOpenButton(false);
		mainFrame.setPbarValue(0);
		Thread t = new Thread(new TranslationRunner(sourceFile, sourceLang, targetLanguages));
		t.start();
	}

	class TranslationRunner implements Runnable {

		private File sourceFile;

		private Language sourceLanguage;

		private Language[] targetLanguages;

		public TranslationRunner(File sourceFile, Language sourceLanguage, Language[] targetLanguages) {
			this.sourceFile = sourceFile;
			this.sourceLanguage = sourceLanguage;
			this.targetLanguages = targetLanguages;
		}

		public void run() {
			if (sourceFile != null) {
				mainFrame.setPbarMaximum(getNumberOfKeys(sourceFile) * targetLanguages.length);
				for (Language lang : targetLanguages) {
					mainFrame.setStatus("Translating to " + lang);
					try {
						new PropertyTranslator(mainFrame).translate(sourceFile, sourceLanguage, lang);
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(mainFrame, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}

				}
			}
			JOptionPane.showMessageDialog(mainFrame, "Translation finished successfully.", "Success", JOptionPane.OK_OPTION);
			mainFrame.resetPbar();
			mainFrame.setStatus("");
			mainFrame.resetGUI();
		}

		private int getNumberOfKeys(File sourceFile) {
			int counter = 0;
			try {
				PropertyResourceBundle propertyBundle = new PropertyResourceBundle(new FileInputStream(sourceFile));
				for (Enumeration e = propertyBundle.getKeys(); e.hasMoreElements();) {
					String key = (String) e.nextElement();
					counter++;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return counter;
		}

	}
}
